package com.xie.leetcode.string;

//290. 单词规律
//        给定一种规律 pattern 和一个字符串 str ，判断 str 是否遵循相同的规律。
//
//        这里的 遵循 指完全匹配，例如， pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。
//
//        示例1:
//
//        输入: pattern = "abba", str = "dog cat cat dog"
//        输出: true
//        示例 2:
//
//        输入:pattern = "abba", str = "dog cat cat fish"
//        输出: false
//        示例 3:
//
//        输入: pattern = "aaaa", str = "dog cat cat dog"
//        输出: false
//        示例 4:
//
//        输入: pattern = "abba", str = "dog dog dog dog"
//        输出: false
//        说明:
//        你可以假设 pattern 只包含小写字母， str 包含了由单个空格分隔的小写字母。

import java.util.HashMap;

/**
 * @author xiezhendong
 * @date 2022/1/14
 */
public class WordPattern {

    public static void main(String[] args) {
        WordPattern wordPattern = new WordPattern();
        System.out.println(wordPattern.wordPattern("abba", "dog cat cat dog"));
        System.out.println(wordPattern.wordPattern("abba", "dog cat cat fish"));
        System.out.println(wordPattern.wordPattern("aaaa", "ddog cat cat dog"));
        System.out.println(wordPattern.wordPattern("abba", "dog dog dog dog"));
    }

    public boolean wordPattern(String pattern, String s) {
        char[] patternArray = pattern.toCharArray();
        String[] sArray = s.split(" ");
        if (patternArray.length != sArray.length) {
            return false;
        }
        HashMap<String, String> pattern2StrMap = new HashMap<>();
        HashMap<String, String> str2PatternMap = new HashMap<>();
        int length = sArray.length;
        for (int i = 0; i < length; i++) {
            char patternOne = patternArray[i];
            String patternOneStr = String.valueOf(patternOne);
            String sOne = sArray[i];
            if (pattern2StrMap.get(patternOneStr) != null && !sOne.equals(pattern2StrMap.get(patternOneStr))) {
                return false;
            }
            if (str2PatternMap.get(sOne) != null && !patternOneStr.equals(str2PatternMap.get(sOne))) {
                return false;
            }
            pattern2StrMap.put(patternOneStr, sOne);
            str2PatternMap.put(sOne, patternOneStr);
        }
        return true;
    }
}
